import { Button, Form, FormInstance, Input, Radio, Select, Upload, UploadFile } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import React, { useEffect, useRef, useState } from "react";
import { RcFile, UploadProps } from "antd/lib/upload";
import { markdownToTxt } from "markdown-to-txt";
import useMessage from "@/hooks/useMessage";
import styles from "./index.module.less";
import { getTagList } from "@/redux/modules/tag/action";
import { useSelector } from "react-redux";
import { RootState } from "@/redux";
import { Subfield } from "@/api/interface/blog";
import { getSubfieldApi, uploadMd } from "@/api/modules/blog";
import { addBlog, getBlogDetail, updateBlog } from "@/redux/modules/blog/action";
import { uploadFile } from "@/api/modules/common";
import { useNavigate } from "react-router-dom";

interface PropsType {
	type?: string;
	visible?: boolean;
	content_text?: string;
	onComfirm?: () => void;
}

const BlogAdd: React.FC<PropsType> = props => {
	const { type, visible } = props;
	const { contextHolder, success } = useMessage();

	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const [mdFile, setMdFile] = useState<UploadFile[]>([]);

	const handleUploadImages = async () => {
		const formData = new FormData();
		fileList.forEach(file => {
			formData.append("file", file as RcFile);
		});
		const res = await uploadFile(formData);
		return res.data;
	};

	const handleUploadMd = async () => {
		const formData = new FormData();
		mdFile.forEach(file => {
			formData.append("file", file as RcFile);
		});
		const res = await uploadMd(formData);
		return res.data;
	};

	const fileUploadProps: UploadProps = {
		onRemove: file => {
			const index = fileList.indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			setFileList(newFileList);
		},
		beforeUpload: file => {
			setFileList([...fileList, file]);
			return false;
		},
		fileList
	};

	const mdFileUploadProps: UploadProps = {
		onRemove: file => {
			const index = mdFile.indexOf(file);
			const newFileList = mdFile.slice();
			newFileList.splice(index, 1);
			setMdFile(newFileList);
		},
		beforeUpload: file => {
			setMdFile([...mdFile, file]);
			return false;
		},
		fileList: mdFile
	};

	const onFinish = async (values: any) => {
		let blog_image, content_html, content_text;
		// 上传文件
		if (fileList.length > 0) {
			const res = await handleUploadImages();
			blog_image = res.images[0].imageUrl;
		}
		if (mdFile.length > 0) {
			const res = await handleUploadMd();
			content_html = res.content_html;
			content_text = res.content_text;
		}
		if (props.content_text) {
			content_html = markdownToTxt(props.content_text).slice(0, 50);
			content_text = props.content_text;
		}
		const form = {
			...values,
			blog_image,
			content_html,
			content_text
		};
		if (type) {
			updateBlog({ ...form, id: blogDetail.id });
		} else {
			addBlog(form);
		}
		props.onComfirm && props.onComfirm();
		success("发布成功");
	};

	useEffect(() => {
		getTagList(1, 999);
		getSubfieldList();
	}, []);

	const tagList = useSelector((state: RootState) => state.tag.tagList);
	const [subfieldList, setSubfieldList] = useState<Subfield[]>([]);
	const getSubfieldList = async () => {
		const res = await getSubfieldApi();
		if (res.code === 200) {
			setSubfieldList(res.data.rows);
		}
	};
	const tagOptions = tagList.map(item => {
		return {
			label: item.tag_name,
			value: item.id
		};
	});
	const subfieldOptions = subfieldList.map(item => {
		return {
			label: item.name,
			value: String(item.id)
		};
	});

	const blogDetail = useSelector((state: RootState) => state.blog.blogDetail);
	const initBlogDetail = { ...blogDetail, tags: blogDetail.tags.map(item => item.id) };
	const formRef = useRef<FormInstance | null>(null);

	useEffect(() => {
		if (type) {
			formRef.current?.resetFields();
		}
	}, [blogDetail, fileList, mdFile]);

	useEffect(() => {
		formRef.current?.setFieldsValue({
			title: "",
			classify: "",
			top: 0,
			tags: []
		});
	}, [visible]);

	const navigate = useNavigate();

	const gotoEditor = (id: number) => {
		getBlogDetail(id);
		navigate(`/blog/editor`, { state: { id: id, edit: true } });
	};

	return (
		<div className={styles.root}>
			{contextHolder}
			{<a onClick={() => gotoEditor(initBlogDetail.id)}>编辑器修改</a>}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={initBlogDetail}
			>
				<Form.Item label="标题" rules={[{ required: true }]} name="title">
					<Input />
				</Form.Item>
				<Form.Item label="标签" rules={[{ required: true }]} name="tags">
					<Select mode="tags" placeholder="选择标签" options={tagOptions} />
				</Form.Item>
				<Form.Item label="分栏" rules={[{ required: true }]} name="classify">
					<Select allowClear options={subfieldOptions} />
				</Form.Item>
				<Form.Item label="置顶" name="top">
					<Radio.Group defaultValue={0}>
						<Radio value={0}> 否 </Radio>
						<Radio value={1}> 是 </Radio>
					</Radio.Group>
				</Form.Item>
				<Form.Item label="文件" valuePropName="fileList">
					<Upload listType="picture-card" {...mdFileUploadProps}>
						<div>
							<PlusOutlined />
							<div style={{ marginTop: 8 }}>上传博客文件</div>
						</div>
					</Upload>
				</Form.Item>
				<Form.Item label="封面" valuePropName="fileList">
					<Upload listType="picture-card" {...fileUploadProps}>
						<div>
							<PlusOutlined />
							<div style={{ marginTop: 8 }}>上传封面</div>
						</div>
					</Upload>
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default BlogAdd;
